package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.Category;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.CategoryBrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import com.leyou.item.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryBrandServiceImpl extends ServiceImpl<CategoryBrandMapper, CategoryBrand> implements CategoryBrandService {


    @Autowired
    private CategoryService categoryService;

    private BrandService brandService;

    @Override
    public List<CategoryDTO> queryCategoryByBrandId(Long bid) {

        // 1.根据品牌id，查询中间表，得到中间表对象集合
        List<CategoryBrand> categoryBrandList = this.query().eq("brand_id", bid).list();

        if (CollectionUtils.isEmpty(categoryBrandList)) {

            return Collections.emptyList();

        }

        // 2. 获取分类id集合
        List<Long> categoryIdList = categoryBrandList
                                        .stream().map(CategoryBrand::getCategoryId)
                                                        .collect(Collectors.toList());

        // 3.根据分类id集合，查询分类对象集合
        List<Category> categoryList = categoryService.listByIds(categoryIdList);

        // 4.转换DTO
        return CategoryDTO.convertEntityList(categoryList);

    }

    @Override
    public List<BrandDTO> queryBrandByCategoryId(Long cid) {

        List<Brand> list = this.baseMapper.queryBrandByCategoryId(cid);

        return BrandDTO.convertEntityList(list);

//        List<Long> brandIds = query()
//                .eq("category_id", cid)
//                .list()
//                .stream()
//                .map(CategoryBrand::getBrandId)
//                .collect(Collectors.toList());
//
//        return BrandDTO.convertEntityList(brandService.listByIds(brandIds));

    }
}
